<?php

namespace Frieza\Modules\Photo\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\cache\PhotoCounter;
use Doraemon\model\Content\ContentCategoryLabel as mContentCategoryLabel;
use Doraemon\model\Member;
use Doraemon\model\Photos;
use Doraemon\service\AppContentSync;
use Doraemon\service\Content\ContentRelatedCategory;
use Doraemon\service\Photos as sPhotos;
use Doraemon\model\Es\Photo;
use Doraemon\model\ContentSignExtend;
use Doraemon\service\ContentCategory;
use Doraemon\service\UserLevel as sUserLevel;
use Doraemon\service\Videos\Videos as sVideos;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Box;
use Illuminate\Http\Request;

class PhotoListController extends Controller
{
    const NOT_CONSUME_GOODS = 0;
    const IS_CONSUME_GOODS = 1;
    const ALL_CONSUME = 2;

    const CONSUME_MAP = [
        self::ALL_CONSUME => '全部',
        self::NOT_CONSUME_GOODS => '不可消费内容',
        self::IS_CONSUME_GOODS => '可消费内容'
    ];

    const DELETED = 9;
    const NORMAL = 1;
    const DELETED_MAP = [
        self::NORMAL => '否',
        self::DELETED => '是',
    ];

    const PHOTO_TYPE_GIF = 'f';//gif
    const PHOTO_TYPE_STILL = 2;//静图

    const NOT_CLASSIFY = '0';

    const EMPOWER = 1;

    const SEARCH_NOTE_TYPE_DESC = [
        self::SEARCH_PHOTO_TYPE_ALL => "全部",
        self::SEARCH_PHOTO_TYPE_PHOTO => "图片",
        self::SEARCH_PHOTO_TYPE_VIDEO => "视频",
        self::SEARCH_PHOTO_TYPE_DIARY => "日记"
    ];

    const SEARCH_PHOTO_TYPE_ALL = 1; //  全部
    const SEARCH_PHOTO_TYPE_PHOTO = 4; //  图片
    const SEARCH_PHOTO_TYPE_VIDEO = 5; //  视频
    const SEARCH_PHOTO_TYPE_DIARY = 6; //日记

    //0级用户搜索专用array
    const SEARCH_LEVEL_0_ARRAY = ['c_level_1', 'c_level_2', 'c_level_3', 'c_level_4', 'c_level_5'];

    public static $product_level = [
        0 => 'Lv0',
        1 => 'Lv1',
        2 => 'Lv2',
        3 => 'Lv3',
        4 => 'Lv4',
        5 => 'Lv5',
        6 => 'Lv6',
        7 => 'Lv7',
    ];

    public static $is_empower = [
        0 => '未授权',
        1 => '已授权',
    ];

    public static $EXPOWER_MAP = [
        self::EMPOWER => '授权轻应用'
    ];

    public function index(Request $request, Content $content)
    {
        Admin::script($this->adminCopy());
        $search = $request->input();
        if ($search['is_deleted'] == self::DELETED && empty($search['uid'])) {
            admin_toastr('搜索删除必须在第一列填写uid', 'error');
        }
        if ($search['is_deleted'] == self::DELETED && !empty($search['uid'])) {
            $pageSize = $request->input("per_page", 20);
            $page = $request->input("page", 1);
            $photos = \Doraemon\service\Photos::getDeletedPhotosByUid($search['uid'], $page, $pageSize);
            if (!empty($photos)) {
                $photoIds = array_column($photos, 'id');
                $total = \Doraemon\model\Photos::getDeletedPhotosNumByUid($search['uid']);
                $photoInfos = $photos;
            } else {
                $total = 0;
                $photoInfos = [];
            }
        } else {
            $result = $this->buildParams($request);
            $photoIds = array_column($result['rows'], 'id');
            $total = $result['total'];
            $photoInfos = sPhotos::getPhotos($photoIds);
        }


        $uids = array_column($photoInfos, 'uid');
        $aEmpowerUser = AppContentSync::getContent(array_unique($uids));
        $userInfos = Member::getUserInfoByIds($uids);
        $nickNames = array_column($userInfos, 'nick', 'uid');
        $extendInfos = ContentSignExtend::getExtendInfoByNoteIds($photoIds);
        if (!empty($extendInfos)) {
            $isConsume = array_column($extendInfos, 'is_consume_goods', 'obj_id');
        } else {
            $isConsume = [];
        }
        //获取分类
        $communityCategorizes = [];
        $categories = ContentCategory::getTypesByObjs($photoIds);
        if ($categories && is_array($categories)) {
            foreach ($categories as $category) {
                $communityCategorizes[$category['obj_id']] = $category['category'];
            }
        }
        //获取品类
        $contentRelatedCategory = ContentRelatedCategory::getTypesByObjIds($photoIds);
        //点赞，收藏，评论 count
        $count = PhotoCounter::getMulti($photoIds);
        //处理数据
        foreach ($photoInfos as $noteId => $photoInfo) {
            if (isset($photoInfo['id'])){
                $photoInfos[$noteId]['note_id'] = $photoInfo['id'];
            }else{
                continue;
            }
            $photoInfos[$noteId]['nickname'] = $nickNames[$photoInfo['uid']];
            $photoInfos[$noteId]['category'] = $communityCategorizes[$noteId];
            $photoInfos[$noteId]['category_first_id'] = $contentRelatedCategory[$noteId]['category_first_id'];
            $photoInfos[$noteId]['category_second_id'] = $contentRelatedCategory[$noteId]['category_second_id'];
            $photoInfos[$noteId]['like'] = $count[$noteId]['like'];
            $photoInfos[$noteId]['favorite'] = $count[$noteId]['favorite'];
            $photoInfos[$noteId]['comment'] = $count[$noteId]['comments'];
            if ($photoInfos[$noteId]['type'] == Photos::TYPE_DIARY) {
                $photoInfos[$noteId]['main'] = self::SEARCH_NOTE_TYPE_DESC[self::SEARCH_PHOTO_TYPE_DIARY];
            }
            if ($photoInfos[$noteId]['show_type'] == Photos::SHOW_TYPE_PHOTO) {
                $photoInfos[$noteId]['main'] = self::SEARCH_NOTE_TYPE_DESC[self::SEARCH_PHOTO_TYPE_PHOTO];
            } elseif ($photoInfos[$noteId]['show_type'] == Photos::SHOW_TYPE_VIDEO) {
                $photoInfos[$noteId]['main'] = self::SEARCH_NOTE_TYPE_DESC[self::SEARCH_PHOTO_TYPE_VIDEO];
            }
            if (isset($isConsume[$noteId])) {
                $photoInfos[$noteId]['is_consume'] = $isConsume[$noteId];
            }
            if ($photoInfo['show_type'] == Photos::SHOW_TYPE_VIDEO) {
                if ($search['is_deleted'] == self::DELETED) {
                    $videoInfo = sVideos::getAllVideoCoverInfoById($photoInfo['video_id']);
                } else {
                    $videoInfo = sVideos::getVideoCoverInfoById($photoInfo['video_id']);
                }

                $photoInfos[$noteId]['expand'] = $this->_getVideoExpand($videoInfo);
            } else {
                $picInfos = json_decode($photoInfo['pic_list'], true) ?: [];
                $photoInfos[$noteId]['expand'] = $this->_getPicExpand($picInfos);
            }
            $photoInfos[$noteId]['expand'] .= $this->_getDivLine();
            $iEmpowerStatus = isset($aEmpowerUser[$photoInfo['uid']]) ?? 0;
            $photoInfos[$noteId]['is_empower'] = self::$is_empower[$iEmpowerStatus];
            $iLevel = sUserLevel::getUserLevel($photoInfo['uid']);
            $photoInfos[$noteId]['product_level'] = self::$product_level[$iLevel];
        }
        //分页
        $options = [
            'perPage' => $request->input('per_page') ?: 20,
            'keyName' => 'note_id'
        ];
        $gridModel = new pGridDataModel($photoInfos, $total, $options);
        $categoryLabelAll = mContentCategoryLabel::getListFormatKey(0, 0);
        $gridList = Admin::grid($gridModel, function (Grid $grid)use ($categoryLabelAll) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->expandFilter();
            $grid->disableActions();
            //过滤器
            $grid->filter(function (Grid\Filter $filter) {
                $this->getFilter($filter);
            });
            //列表
            $grid->column('note_id', 'ID')->expand(function () {
                return $this->expand;
            }, true)->width(90);
            $grid->column('uid', '用户信息')->display(function () {
                return '<strong>[uid]:</strong>' . $this->uid . "<br>" .
                    '<strong>[昵称]:</strong>' . "<br>" . $this->nickname . "<br><br>" .
                    '<strong>[生产等级]:</strong>' . $this->product_level . "<br><br>" .
                    '<strong>[授权]:</strong>' . $this->is_empower . "<br><br>" .
                    "<a href='javascript:;' class='btn btn-default copyH5'  data-id='$this->note_id' >复制链接</a>";
            })->width(120);
            $grid->column('remark', '图说')->display(function () {
                return "<strong>[字数]: </strong>" .
                    mb_strlen(preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/", "", strip_tags($this->remark))) . "<br>
                    <strong>[标题]:</strong>$this->title<br>
                    <strong>[类型]:</strong>$this->main<br>
                    <strong>[正文]:</strong><br>" . str_replace(' ', '&nbsp;', nl2br($this->remark));
            })->width(300);
            $grid->column('quality', '质量')->display(function () use ($categoryLabelAll){
                if ($this->admin_score <= 30 && $this->admin_score > 20) {
                    $score = Photos::QUALITY_ORDINARY;
                } else if ($this->admin_score > 30 && $this->admin_score < 80) {
                    $score = Photos::QUALITY_HIGH;
                } else if ($this->admin_score < 6 && $this->admin_score > 0) {
                    $score = Photos::QUALITY_LOW;
                } else if ($this->admin_score >= 80) {
                    $score = Photos::QUALITY_FEATURED;
                } else {
                    $score = Photos::QUALITY_PENDING;
                }
                switch ($score) {
                    case Photos::QUALITY_LOW:
                        return "<h3><span class='label label-danger'>" . Photos::QUALITY_DESC[Photos::QUALITY_LOW] . "</span></h3><br>";
                    case Photos::QUALITY_ORDINARY:
                        return "<h3><span class='label label-warning'>" . Photos::QUALITY_DESC[Photos::QUALITY_ORDINARY] . "</span></h3><br>";
                    case Photos::QUALITY_HIGH:
                        return "<h3><span class='label label-info'>" . Photos::QUALITY_DESC[Photos::QUALITY_HIGH] . "</span></h3><br>";
                    case Photos::QUALITY_FEATURED:
                        return "<h3><span class='label label-success'>" . Photos::QUALITY_DESC[Photos::QUALITY_FEATURED] . "</span></h3><br>";
                    case Photos::QUALITY_PENDING:
                    default:
                        return "<h3><span class='label label-default'>" . Photos::QUALITY_DESC[Photos::QUALITY_PENDING] . "</span></h3><br>";
                }
            })->width(70);
            $grid->column('is_consume', '是否为可消费内容')->display(function ()use ($categoryLabelAll) {
                if ($this->is_consume == ContentSignExtend::IS_CONSUME_GOODS) {
                    return "<p class='text-center'>" . "是" . "</p>";
                }
                if ($this->is_consume == ContentSignExtend::NOT_CONSUME_GOODS) {
                    return "<p class='text-center'>" . "否" . "</p>";
                }
            })->width(140);
            $grid->column('addtime', '发布时间')->display(function () {
                return date('Y-m-d H:i:s', $this->addtime);
            })->width(150)->sortable();
            $grid->column('like', '点赞数')->sortable()->width(80);
            $grid->column('favorite', '收藏数')->sortable()->width(80);
            $grid->column('comment', '评论数')->sortable()->width(80);

            $grid->column('category', '品类')->display(function () use ($categoryLabelAll) {
                $categoryFirstId = $categoryLabelAll[$this->category_first_id] ?? '';
                $categorySecondId = $categoryLabelAll[$this->category_second_id] ?? '';
                $result = "<p>一级：{$categoryFirstId}</p>";
                $result .= "<p>二级：{$categorySecondId}</p>";
                return $categorySecondId ? $result : '';
            });
        });
        Admin::script($this->imgScript());
        return $content->body($gridList)
            ->header('Note列表页')
            ->row("<div style='position:fixed;z-index:10000;top:50px;left:35%;width:600px;height:600px;' class='imgMoveDiv'><img src='' alt='' class='imgMove' style='width:auto;height:auto;max-width:100%;max-height:100%;'></div>");
    }

    private function getFilter(Grid\Filter $filter)
    {
        $categoryFirstId = request('category_first_id', null);
        $categoryLabelSecond = [];
        if ($categoryFirstId) {
            $categoryLabelSecond = mContentCategoryLabel::getListFormatKey($categoryFirstId, 2);
        }
        $categoryLabelFirst = mContentCategoryLabel::getListFormatKey(0, 1);
        $filter->disableIdFilter();
        $filter->column(4, function ($filter) {
            $filter->dropDown('search_id', [
                'note_id' => 'note id',
                'uid' => '用户id'
            ]);
            $filter->dropDown('search_keyword', [
                'title' => '标题',
                'remark' => '描述']);
            $filter->equal('level', '生产等级')->checkbox(self::$product_level);
            $filter->equal('is_sync', '用户授权')->checkbox(self::$EXPOWER_MAP);
        }
        );

        $filter->column(4, function (Grid\Filter $filter)use ($categoryLabelSecond,$categoryLabelFirst) {
            $filter->equal('topic_id', '话题id');

            $filter->equal('category_first_id', '一级品类')->select($categoryLabelFirst)->load('category_second_id', route('getCategoryLabel'));
            $filter->equal('category_second_id', '二级品类')->select($categoryLabelSecond);

            $filter->equal('quality', '质量')->checkbox(Photos::QUALITY_DESC);
        });

        $filter->column(4, function (Grid\Filter $filter) {
            $filter->between('time', '发布时间')->date();
            $filter->equal('show_type', '类型')
                ->radio(self::SEARCH_NOTE_TYPE_DESC);
            $filter->equal('is_consume', '消费内容')->radio(self::CONSUME_MAP);
            $filter->equal('is_deleted', '是否删除')->radio(self::DELETED_MAP);

        });
    }

    //处理条件
    private function buildParams(Request $request)
    {
        $search = $request->input();
        $pageSize = $request->input("per_page", 20);
        $page = $request->input("page", 1);
        $defaultResult = [
            'rows' => [],
            'total' => 0
        ];
        //若以note_id为索引将不考虑其他参数
        if (!empty($search['note_id'])) {
            $defaultResult['rows'][] = ['id' => $search['note_id']];
            $defaultResult['total'] = 1;
            return $defaultResult;
        }

        $where = [];
        if (isset($search['uid']) && is_numeric($search['uid'])) {
            $where['uid'] = $search['uid'];
        }
        //time
        if (!isset($search['time']['end'], $search['time']['start'])) {
            $request->merge([
                'time' => [
                    'start' => '2015-01-01',
                    'end' => date('Y-m-d H:i:s'),
                ]
            ]);
            $search['time']['start'] = '2015-01-01';
            $search['time']['end'] = date('Y-m-d H:i:s');
        }
        if (isset($search['time']['start']) && $search['time']['start'] !== '') {
            $where['addtime[>=]'] = strtotime($search['time']['start']);
        }
        //结束时间
        if (isset($search['time']['end']) && $search['time']['end'] !== '') {
            $where['addtime[<=]'] = strtotime($search['time']['end']);
        }
        //分数
        if (isset($search['quality'])) {
            $where['quality'] = $search['quality'];
        }
        //是否可消费内容
        if (isset($search['is_consume']) && $search['is_consume'] != self::ALL_CONSUME) {
            $where['is_consume_goods'] = $search['is_consume'];
        }
        //话题id
        if (isset($search['topic_id']) && $search['topic_id'] != null) {
            $where['topic_activity_id'] = $search['topic_id'];
        }
        //note类型  默认type_all 全查
        if (isset($search['show_type']) && $search['show_type'] != self::SEARCH_PHOTO_TYPE_ALL) {
            switch ($search['show_type']) {
                case self::SEARCH_PHOTO_TYPE_PHOTO:
                    $where["show_type"] = Photos::SHOW_TYPE_PHOTO;
                    break;
                case self::SEARCH_PHOTO_TYPE_VIDEO:
                    $where["show_type"] = Photos::SHOW_TYPE_VIDEO;
                    break;
                case self::SEARCH_PHOTO_TYPE_DIARY:
                    $where["show_type"] = Photos::SHOW_TYPE_TEXT;
                    break;
            }
        }
        //分类
        if (isset($search['category']) && !empty($search['category']) && is_array($search['category'])) {
            if (in_array(self::NOT_CLASSIFY, $search['category'])) {
                foreach ($search['category'] as $category) {
                    if ($category === self::NOT_CLASSIFY) {
                        $where['OR']['content_categorys.keyword'] = '';
                    } else {
                        $where['OR']['content_categorys'][] = $category;
                    }
                }
            } else {
                $where['content_categorys'] = $search['category'];
            }
        }
        //品类搜索
        if (isset($search['category_first_id']) && $search['category_first_id'] != null) {
            $where['category_first_id'] = $search['category_first_id'];
        }
        if (isset($search['category_second_id']) && $search['category_second_id'] != null) {
            $where['category_second_id'] = $search['category_second_id'];
        }
        //标题或描述关键词搜索
        if (!empty($search['title'])) {
            $where['title'] = $search['title'];
        }
        if (!empty($search['remark'])) {
            $where['text_remark'] = $search['remark'];
        }
        //用户生产等级
        if (isset($search['level'])) {
            foreach ($search['level'] as $level) {
                //0级不加格外的条件
                if ($level == 0) {
                    $where['OR']['master_tag[!]'] = self::SEARCH_LEVEL_0_ARRAY;
                    continue;
                }
                $where['OR']['master_tag'][] = 'c_level_' . $level;
            }
        }
        //轻应用授权
        if (isset($search['is_sync']) && in_array(self::EMPOWER, $search['is_sync'])) {
            $where['master_tag'] = 'is_ali_sync';
        }
        if (isset($search['_sort'])) {
            if ($search['_sort']['type'] === 'desc') {
                $order = Photo::DESC;
            } else {
                $order = Photo::ASC;
            }
            $where['ORDER'] = [$search['_sort']['column'] => $order];
        } else {
            $where['ORDER'] = ['addtime' => Photo::DESC];
        }
        $where['LIMIT'] = [($page - 1) * $pageSize, $pageSize];
        //ES搜索
        $esResult = Photo::getNoteListByParams($where, 'id');
        $result['rows'] = $esResult['rows'] ? array_values($esResult['rows']) : [];
        $result['total'] = (int)$esResult['total'];
        return $result;
    }

    private function _getVideoExpand($videoInfo)
    {
        $row = new Row();
        $row->column(4, "<video class='img-responsive container-fluid' controls src='{$videoInfo['basicInfo']['play_url_for_frieza']}' ></video>");
        $content = "<img class='img-responsive float-left center-block col-md-2' src='{$videoInfo['basicInfo']['ori_pic_url']}' />";
        $content = $content . implode("", array_map(function ($snapshotImg) {
                return "<img class='img-responsive float-left center-block col-md-2' src='{$snapshotImg}' />";
            }, (array)$videoInfo['snapshot']));
        $row->column(8, $content);
        $box = new Box('视频信息');
        $box->solid()->content($row->render());
        return $box->render();
    }

    private function _getPicExpand($picInfos)
    {
        $row = new Row();
        $row->column(12, implode("", array_map(function ($picInfo) {
            $imgUrl = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $picInfo['pic_id'], ImgUrl::IMAGE_SIZE_ORI_NPHONE);
            return "<img class='img-responsive float-left center-block col-md-2 img' src='{$imgUrl}' />";
        }, (array)$picInfos)));
        $box = new Box('图片信息' . '  (数量:' . count($picInfos) . ')');
        $box->solid()->content($row->render());
        return $box->render();
    }

    private function _getDivLine()
    {
        return "<div style='width:100%;height:5px;background-color:#4169E1;margin-bottom:20px;'></div>";
    }

    public function imgScript()
    {
        return <<<SCRIPT
            $('.imgMoveDiv').hide();
            $('.img').click(function() {
                $('.imgMove').attr('src', $(this).attr('src'));
                $('.imgMoveDiv').show();      
            });
            $('.imgMoveDiv').click(function() {
                $('.imgMoveDiv').hide();      
            });
SCRIPT;
    }

    public function copyUrl($id)
    {
        return Hhzurl::h5PhotoShow($id);
    }

    public function adminCopy()
    {
        return <<<SCRIPT
        $('.copyH5').click(function() {
            var id = $(this).data('id');
            $.ajax({type:"get",url:"copy/"+id,success:function(url){
            var tempInput = document.createElement("input");
            tempInput.value = url;
            document.body.appendChild(tempInput);
            tempInput.select();
            document.execCommand("copy");
            document.body.removeChild(tempInput);
            }});
        });
SCRIPT;
    }
}